package com.jingyanzi.privilege.init;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.jingyanzi.privilege.dao.SecurityBtnMapper;
import com.jingyanzi.privilege.dao.SecurityMenuMapper;
import com.jingyanzi.privilege.domain.BtnDO;
import com.jingyanzi.privilege.domain.ResourceDO;
import com.jingyanzi.privilege.entity.SecurityBtn;
import com.jingyanzi.privilege.entity.SecurityBtnExample;
import com.jingyanzi.privilege.entity.SecurityMenu;
import com.jingyanzi.privilege.entity.SecurityMenuExample;
import com.jingyanzi.privilege.init.InitData;

@Service("initData")
public class InitBtnsData implements InitData {
	
	@Autowired
	private SecurityBtnMapper btnMapper;
	
	@Autowired
	private SecurityMenuMapper menuMapper;

	@Override
	public boolean init(ResourceDO res) throws Exception {
		Gson gson = new Gson();
		
		BufferedReader jsonIn = new BufferedReader(
				new InputStreamReader(new FileInputStream(res.getPath() + res.getName()), "UTF-8"), 50 * 1024 * 1024);
		
		JsonParser parser = new JsonParser();
		
		String json = new String(parser.parse(jsonIn).toString().getBytes());
		
		List<BtnDO> btnsDO = gson.fromJson(json, new TypeToken<List<BtnDO>>() {
		}.getType());

		SecurityBtnExample example1 = new SecurityBtnExample();
		example1.createCriteria().andIdGreaterThan(0);
		btnMapper.deleteByExample(example1);
		int count = 0;
		int id = 0;
		for (BtnDO btn : btnsDO) {
			SecurityMenuExample example = new SecurityMenuExample();
		
			id = Math.abs(btn.getMenuCode().hashCode() - btn.getCode().hashCode());
		
			example.createCriteria().andCodeEqualTo(btn.getMenuCode());
			List<SecurityMenu> list = menuMapper.selectByExample(example);
			SecurityMenu menu = list.get(0);
		
			SecurityBtn entity = new SecurityBtn();
			entity.setId(id);
			entity.setName(btn.getName());
			entity.setMenuCode(btn.getMenuCode());
			entity.setMenuId(menu.getId());
			entity.setCode(btn.getCode());
			entity.setStatus(1);
			entity.setIsDelete(1);
			entity.setCreatetime(new Date());
			entity.setSortNum(0);
			
			btnMapper.insertSelective(entity);
			count++;
		}
		System.out.println("加载按钮："+count);
		return true;
	}

}
